package action;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import actionform.TopicForm;
import dao.TopicMagDao;
import dao.impl.TopicMagImpl;
import domain.Manager;
import domain.Student;
import domain.Teacher;
import domain.Topic;

/**
 * 主题（提问，讨论）处理Action
 * 
 * May 17, 2009
 *
 * @author Fabian
 *
 */
public class TopicManagerAction extends DispatchAction {
	/**
	 * 浏览所有主题的Action，但是要传递分页参数（start--开始，limit--间隔）
	 */
	public ActionForward show(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String discuss_question = request.getParameter("flag");
		
		TopicForm tf = (TopicForm)form;
		int start = tf.getStart();
		int limit = tf.getLimit();
		
		if ("question".equals(discuss_question)) {			//显示所有的提问
			
			TopicMagDao tmd = new TopicMagImpl();
			//获取此页面的问题
			List<Topic> list = tmd.getPageQuestion(start, limit);
			//获取总记录数
			int totalCount = tmd.getQuestionTotalCount();
			
			//组装JSON字符串，返回
			String resultArray = "";
			for (Iterator<Topic> it = list.iterator(); it.hasNext(); ) {
				Topic t = it.next();
				Date d = t.getPubDate();
				long tt = d.getTime();
				resultArray = resultArray + "{id: " + t.getId() + ", title: '" + t.getTitle() +
								"', status: '" + t.getStatus() + "', reply_count: " + 
								t.getReply_count() + ", author: '" + t.getAuthor() +
								"', role: '" + t.getRole() + "', pubdate: new Date(" + tt +
								"), content: '" + t.getContent() + "'}";
				if (it.hasNext()) {
					resultArray = resultArray + ",";
				}			
			}
			
			String jsonStr = "";
			jsonStr = "{totalProperty: " + totalCount + ", root: [ " + resultArray + " ]}";
			
			request.setAttribute("result", jsonStr);
					
			return mapping.findForward("show_result");
			
		} else if ("discuss".equals(discuss_question)) {	//显示所有的讨论
			
			TopicMagDao tmd = new TopicMagImpl();
			//获取此页面的问题
			List<Topic> list = tmd.getPageDiscussion(start, limit);
			//获取总记录数
			int totalCount = tmd.getDiscussionTotalCount();
			
			//组装JSON字符串，返回
			String resultArray = "";
			for (Iterator<Topic> it = list.iterator(); it.hasNext(); ) {
				Topic t = it.next();
				Date d = t.getPubDate();
				long tt = d.getTime();
				resultArray = resultArray + "{id: " + t.getId() + ", title: '" + t.getTitle() +
								"', status: '" + t.getStatus() + "', reply_count: " +
								t.getReply_count() + ", author: '" + t.getAuthor() +
								"', role: '" + t.getRole() + "', pubdate: new Date(" + tt +
								"), content: '" + t.getContent() + "'}";
				if (it.hasNext()) {
					resultArray = resultArray + ",";
				}			
			}
			
			String jsonStr = "";
			jsonStr = "{totalProperty: " + totalCount + ", root: [ " + resultArray + " ]}";
			
			request.setAttribute("result", jsonStr);
					
			return mapping.findForward("show_result");
			
		}			
		
		return mapping.findForward("show_result");
	}
	
	/**
	 * 删除问题或讨论，要传递Topic的id
	 */
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		TopicForm tf = (TopicForm)form;
		int del_id = tf.getId();
		
		TopicMagDao tmd = new TopicMagImpl();
		boolean result = tmd.delTopic(del_id);
		
		//组装返回的JSON数据
		String returnStr = "";
		if (result) {
			
			returnStr = "{result: 'success', msg: '恭喜，删除话题成功！'}";
			request.setAttribute("result", returnStr);
			
		} else {
			
			returnStr = "{result: 'failure', msg: '抱歉，删除话题失败！请重新尝试！'}";
			request.setAttribute("result", returnStr);
			
		}		
		
		return mapping.findForward("del_result");
	}
	
	/**
	 * 关闭问题或讨论，要传递Topic的id
	 */
	public ActionForward close(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		TopicForm tf = (TopicForm)form;
		int close_id = tf.getId();
		
		TopicMagDao tmd = new TopicMagImpl();
		boolean result = tmd.closeTopic(close_id);
		
		//组装返回的JSON数据
		String returnStr = "";
		if (result) {
			
			returnStr = "{result: 'success'}";
			request.setAttribute("result", returnStr);
			
		} else {
			
			returnStr = "{result: 'failure'}";
			request.setAttribute("result", returnStr);
			
		}		
		
		return mapping.findForward("close_result");
	}
	
	/**
	 * 添加问题或讨论
	 */
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String discuss_question = request.getParameter("flag");
		
		if ("question".equals(discuss_question)) {			//添加提问
			
			TopicForm tf = (TopicForm)form;
			String title = tf.getTitle();
			String content = tf.getContent();		
			
			//获取发布人的信息
			HttpSession session = request.getSession();
			Object user = session.getAttribute("user");
			
			if (user == null) {
				return null;
			}
			
			int user_id = 1;
			int role = 3;
			if (user instanceof Manager) {
				Manager m = (Manager)user;
				user_id = m.getId();
				role = 1;
			} else if (user instanceof Teacher) {
				Teacher m = (Teacher)user;
				user_id = m.getId();
				role = 2;
			} else if (user instanceof Student) {
				Student m = (Student)user;
				user_id = m.getId();
				role = 3;
			}
			
			
			
			Topic t = new Topic();
			t.setTitle(title);
			t.setContent(content);
			t.setUser_id(user_id);
			t.setRole_id(role);			
			
			TopicMagDao tmd = new TopicMagImpl();
			boolean result = tmd.addQuestion(t);
			
			//组装返回的JSON数据
			String returnStr = "";
			if (result) {
				
				returnStr = "{success: true, msg: '恭喜，提问成功！'}";
				request.setAttribute("result", returnStr);
				
			} else {
				
				returnStr = "{failure: true, msg: '抱歉，提问失败！请重新尝试！'}";
				request.setAttribute("result", returnStr);
				
			}		
			return mapping.findForward("add_result");
			
		} else if ("discuss".equals(discuss_question)) {	//添加讨论
			
			TopicForm tf = (TopicForm)form;
			String title = tf.getTitle();
			String content = tf.getContent();		
			
			//获取发布人的信息
			HttpSession session = request.getSession();
			Object user = session.getAttribute("user");
			
			if (user == null) {
				return null;
			}
			
			int user_id = 1;
			int role = 3;
			if (user instanceof Manager) {
				Manager m = (Manager)user;
				user_id = m.getId();
				role = 1;
			} else if (user instanceof Teacher) {
				Teacher m = (Teacher)user;
				user_id = m.getId();
				role = 2;
			} else if (user instanceof Student) {
				Student m = (Student)user;
				user_id = m.getId();
				role = 3;
			}		
			
			Topic t = new Topic();
			t.setTitle(title);
			t.setContent(content);
			t.setUser_id(user_id);
			t.setRole_id(role);			
			
			TopicMagDao tmd = new TopicMagImpl();
			boolean result = tmd.addDiscussion(t);
			
			//组装返回的JSON数据
			String returnStr = "";
			if (result) {
				
				returnStr = "{success: true, msg: '恭喜，发起讨论成功！'}";
				request.setAttribute("result", returnStr);
				
			} else {
				
				returnStr = "{failure: true, msg: '抱歉，发起讨论失败！请重新尝试！'}";
				request.setAttribute("result", returnStr);
				
			}		
			
			return mapping.findForward("add_result");
		}			
		
		return mapping.findForward("add_result");
	}
}
